Python中date包/time包/datetime包的相关知识

您所在的位置:网站首页 python datetime模块安装 Python中date包/time包/datetime包的相关知识

Python中date包/time包/datetime包的相关知识

2023-08-05 18:46| 来源: 网络整理| 查看: 265

官方文档地址:https://docs.python.org/2.7/library/time.html#module-time

参考博客:http://tech.glowing.com/cn/dealing-with-timezone-in-python/

需求:获取某用户所在时区对应服务器所在时区的时间戳。

Python为我提供了datetime,time,calendar模块 常用的还有一个第三方模块pytz

datetime模块定义了如下类:

datetime.date - 理想化的日期对象,假设使用格力高历,有year, month, day三个属性 datetime.time - 理想化的时间对象,不考虑闰秒(即认为一天总是24*60*60秒),有hour, minute, second, microsecond, tzinfo五个属性 datetime.datetime - datetime.date和datetime.time的组合 datetime.timedelta - 后面我们会用到的类,表示两个datetime.date, datetime.time或者datetime.datetime之间的差。 datetime.tzinfo - 时区信息

time模块提供了各种时间操作转换的方法。

calendar模块则是提供日历相关的方法。

pytz模块,使用Olson TZ Database解决了跨平台的时区计算一致性问题,解决了夏令时带来的计算问题。由于国家和地区可以自己选择时区以及是否使用夏令时,所以pytz模块在有需要的情况下得更新自己的时区以及夏令时相关的信息。比如当前pytz版本的OLSON_VERSON = ‘2013g’, 就是包括了Morocco可以使用夏令时。

客户端在收集用户的timezone信息时,常见的错误是:选择保存所在时区的偏移值,例如对于中国的时区,会保存+8,但这样显然丢失了用户所在的时区,即使是同样的时间偏移,也可能对应多个国家和地区。其次,若用户所在地区采用夏令时,这样在每年开始和结束夏令时的时候,偏移值都会发生变化。

可以引入第三方模块pytz后查看全球的时区timezon。

引入datetime.datetime

datetime.fromtimestamp()函数介绍

classmethod datetime.fromtimestamp(timestamp, tz=None)

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

Else tz must be an instance of a class tzinfo subclass, and the timestamp is converted to tz‘s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).

When you don't specify a time zone, not only does it use the local time zone, but the result is naive. 

具体如图所示:

问题如下:int(time.mktime(time.strptime('2018-06-25', "%Y-%m-%d")))

当我们想将这个日期转化为时间戳时,会出现一个问题。这个问题是由于服务器所在时区不一致出现的。

mktime()函数是从local time算起 故当服务器位于UTC时区时 不会出现问题 但当服务器位于例如北京时区时,这个时候返回的时间戳就会少8个小时。再用gmtime()函数转化为struct_time格式时 就会变成2018-06-24-16:00

解决方法:放弃mktime()函数  使用calendar.timegm()函数

或者int(time.mktime(time.strptime('2018-06-25', "%Y-%m-%d"))) -time.altzone

time.altzone的解释:

The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3